package com.ruoyi.web.controller;

import com.ruoyi.utils.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 生成验证码
 *
 * @author huangshun
 */
@RequestMapping("/verifycode")
@Controller
public class VerifyCodeController {


    @Autowired
    private RedisService redisService;


    /* 获取验证码图片 */

    @GetMapping("/getimage")
    public void getVerificationCode(HttpServletResponse response, HttpServletRequest request) {
        try {

            String codeKey = request.getParameter("codeKey");

            int width = 100;

            int height = 40;
            // 生成公式
            String expression = createExpression();
            //计算结果值
            Map<String, Object> calculate = calculate(expression);
            //存储结果到token中
            Object result = calculate.get("result");
            String ax = calculate.get("ax").toString();
            BufferedImage verifyImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

            // 生成对应宽高的初始图片
            String randomText = drawRandomMultiplyText(width, height, verifyImg, ax);

            //结果存储到redis 中 时间5分钟
            redisService.put(codeKey,result.toString(),5*60);

            // 单独的一个类方法，出于代码复用考虑，进行了封装。
            // 功能是生成验证码字符并加上噪点，干扰线，返回值为验证码字符
            response.setContentType("image/png");// 必须设置响应内容类型为图片，否则前台不识别
            OutputStream os = response.getOutputStream(); // 获取文件输出流
            ImageIO.write(verifyImg, "png", os);// 输出图片流
            os.flush();
            os.close();// 关闭流
        } catch (IOException e) {

            e.printStackTrace();

        }

    }

    public static String drawRandomText(int width, int height, BufferedImage verifyImg) {

        Graphics2D graphics = (Graphics2D) verifyImg.getGraphics();

        graphics.setColor(Color.WHITE);// 设置画笔颜色-验证码背景色

        graphics.fillRect(0, 0, width, height);// 填充背景

        graphics.setFont(new Font("微软雅黑", Font.BOLD, 18));

        // 数字和字母的组合

        String baseNumLetter = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";

        StringBuffer sBuffer = new StringBuffer();

        int x = 5; // 旋转原点的 x 坐标

        String ch = "";

        Random random = new Random();

        for (int i = 0; i < 4; i++) {

            graphics.setColor(getRandomColor());

            // 设置字体旋转角度

            int degree = random.nextInt() % 30; // 角度小于30度

            int dot = random.nextInt(baseNumLetter.length());
            ch = baseNumLetter.charAt(dot) + "";
            sBuffer.append(ch);
            // 正向旋转
            graphics.rotate(degree * Math.PI / 180, x, 20);

            graphics.drawString(ch, x, 20);

            // 反向旋转

            graphics.rotate(-degree * Math.PI / 180, x, 20);

            x += 28;

        }
        System.out.println(sBuffer.toString());
        // 画干扰线

		/*for (int i = 0; i < 6; i++) {

			// 设置随机颜色

			graphics.setColor(getRandomColor());

			// 随机画线

			graphics.drawLine(random.nextInt(width), random.nextInt(height),

					random.nextInt(width), random.nextInt(height));

		}*/

        // 添加噪点
        for (int i = 0; i < 30; i++) {
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            graphics.setColor(getRandomColor());
            graphics.fillRect(x1, y1, 2, 2);
        }
        return sBuffer.toString();

    }

    public static String drawRandomMultiplyText(int width, int height, BufferedImage verifyImg, String ax) {

        Graphics2D graphics = (Graphics2D) verifyImg.getGraphics();

        graphics.setColor(Color.WHITE);// 设置画笔颜色-验证码背景色

        graphics.fillRect(0, 0, width, height);// 填充背景

        graphics.setFont(new Font("微软雅黑", Font.BOLD, 18));

        // 数字和字母的组合
        StringBuffer sBuffer = new StringBuffer();
        int x = 5; // 旋转原点的 x 坐标
        String ch = "";
        Random random = new Random();
        // 渲染公式
        for (int i = 0; i < ax.length(); i++) {
            graphics.setColor(getRandomColor());
            // 设置字体旋转角度
            int degree = random.nextInt() % 30; // 角度小于30度
            ch = ax.charAt(i)+"";
            sBuffer.append(ch);
            graphics.drawString(ch, x, 20);
            x += 15;
        }
        System.out.println(sBuffer.toString());
        // 添加噪点
      /*  for (int i = 0; i < 30; i++) {

            int x1 = random.nextInt(width);

            int y1 = random.nextInt(height);

            graphics.setColor(getRandomColor());

            graphics.fillRect(x1, y1, 2, 2);

        }*/
        return sBuffer.toString();

    }

    /**
     * 随机取色
     */

    private static Color getRandomColor() {
        Random ran = new Random();
        Color color = new Color(0,0,0);
        return color;

    }

    /**
     * 随即取x,y为1-100之间，x可以整除y的y值
     *
     * @param x
     * @param y
     * @return
     */
    private static int decide(int x, int y) {//通过递归实现整除
        Random random = new Random();
        String baseNumLetter = "123456789";
        if (x % y != 0) {
            int dot = random.nextInt(baseNumLetter.length());
            String num = baseNumLetter.charAt(dot)+"";
            y = Integer.valueOf(num);
            return decide(x, y);
        } else {
            return y;
        }
    }


    /*
    * 方法名
    * 描述 TODO  计算结果
    * 作者:黄顺
    * 时间 2021/5/31 0031 15:46
    * @Param
    */
    static ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript");
    private static Map<String,Object> calculate(String ax) {
        Map<String, Object> map = new HashMap<>();
        try {
                map.put("ax",ax+"=?");
                map.put("result",jse.eval(ax));
            } catch (ScriptException e) {
                map.put("ax","1+1=?");
                map.put("result","2");
                e.printStackTrace();
            }
        return map;
    }
    /*
    * 方法名 createExpression
    * 描述 TODO 创建运算公式
    * 作者:黄顺
    * 时间 2021/5/31 0031 15:47
    * @Param []
    */
    public static  String createExpression (){
        String baseNumLetter = "123456789";
        char[] operators = new char[]{'+', '-', '*', '/'};
        Random random = new Random();
        int n = 1; //3-5个运算符
        int[] number = new int[n + 1];
        String ex = new String();
        for (int j = 0; j <= n; j++) {
            int dot = random.nextInt(baseNumLetter.length());
            String num = baseNumLetter.charAt(dot)+"";
            number[j] = Integer.valueOf(num);
        }
        int s = random.nextInt(4);//随机选择某个运算符
        ex += String.valueOf(number[0]) + String.valueOf(operators[s]);///5+4+6+9
        if (s == 3) {
            number[0 + 1] = decide(number[0], number[0 + 1]);
        }
        ex += String.valueOf(number[n]);
        return ex;
    }



}
